package com.ciaojian.store.service;

import com.ciaojian.core.enums.business.MaterialApplyRecordStatusEnum;
import com.ciaojian.core.mapper.MaterialMapper;
import com.ciaojian.core.model.Material;
import com.ciaojian.core.model.MaterialApplyRecord;
import com.ciaojian.core.model.MaterialApplyRecordMaterial;
import com.ciaojian.core.model.StoreMaterial;
import com.ciaojian.core.service.MaterialApplyRecordService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Atlakyn
 */
@Service
public class MaterialApplyRecordServiceImpl extends MaterialApplyRecordService {
    @Resource
    private MaterialApplyRecordMaterialServiceImpl materialApplyRecordMaterialService;
    @Resource
    private StoreMaterialServiceImpl storeMaterialService;
    @Resource
    private MaterialMapper materialMapper;

    /**
     * 申请审核
     */
    public boolean applyAudit(MaterialApplyRecord record, MaterialApplyRecordStatusEnum status) {
        switch (status) {
            case DISMISSED:
                record.setStatus(MaterialApplyRecordStatusEnum.DISMISSED);
                break;
            case PASS:
                record.setStatus(MaterialApplyRecordStatusEnum.PASS);
                // 物资申请记录-物资 关联表
                List<MaterialApplyRecordMaterial> materialApplyRecordMaterialList =
                        materialApplyRecordMaterialService.lambdaQuery()
                                .eq(MaterialApplyRecordMaterial::getApplyId, record.getId())
                                .list();
                // 门店库存列表
                List<StoreMaterial> storeMaterialList = storeMaterialService.lambdaQuery().eq(StoreMaterial::getStoreId, record.getStoreId()).list();
                materialApplyRecordMaterialList.forEach(item -> {
                    for (StoreMaterial storeMaterial : storeMaterialList) {
                        if (item.getMaterialId().equals(storeMaterial.getMId())) {
                            storeMaterial.setNum(storeMaterial.getNum() + item.getNum());
                            storeMaterial.updateById();
                            return;
                        }
                    }
                    Material material = new Material().selectById(item.getMaterialId());
                    StoreMaterial storeMaterial = new StoreMaterial();
                    storeMaterial.setStoreId(record.getStoreId())
                            .setName(material.getName())
                            .setType(material.getType())
                            .setUnit(material.getUnit())
                            .setNum(item.getNum())
                            .setMId(material.getId())
                            .insert();
                });
            default:
                break;
        }
        return record.updateById();
    }
}
